/* eslint-disable no-unused-vars */
import namespace from "../../namespace";

class MatrixSeatPolicy extends namespace.policy.canvas.RowSeatPolicy {
  NAME = `${namespace.namespace}.policy.canvas.MatrixSeatPolicy`;

  constructor() {
    super();
  }

  /**
   * @inheritdoc
   * @param {*} x
   * @param {*} y
   */
  drawFeakeSeats(x, y) {
    let row = this.calcSeatTotla(Math.abs(this.startPoint.x - x));
    let col = this.calcSeatTotla(Math.abs(this.startPoint.y - y));

    this.row = row;
    this.col = col;

    let dirX = this.startPoint.x - x < 0 ? 1 : -1;
    let dirY = this.startPoint.y - y < 0 ? 1 : -1;

    let space = this.seatDiameter / 2 + this.seatSpace * 2;

    let count = row * col;

    let overage = this.seats.length - count;

    // 删除多余图形
    if (overage >= 0) {
      new Array(overage).fill("").forEach(() => {
        let shape = this.seats.pop();
        shape.setCanvas(null);
      });
    }

    let index = 0;
    for (let i = 0; i < row; i++) {
      for (let j = 0; j < col; j++) {
        let newX = this.startPoint.x + i * space * dirX;
        let newY = this.startPoint.y + j * space * dirY;

        let shape = this.seats[index];
        if (!shape) {
          shape = new namespace.shape.SeatCircle({
            diameter: this.seatDiameter,
            x: 0,
            y: 0,
            alpha: 0.5
          });

          shape.setCanvas(this.canvas);
          this.seats.push(shape);
        }

        shape.setCenter(newX, newY);

        index++;
      }
    }

    return count;
  }

  // 绘制总数文案
  drawCountText(total) {
    if (!this.totalTextTip) {
      this.totalTextTip = this.canvas.paper.text(x, y, "");
    }

    if (total < 3) {
      this.totalTextTip.attr({ text: "" });
      return;
    }

    let { x, y } = this.endPoint;
    this.totalTextTip.attr({
      x: x + 20,
      y: y + 20,
      text: `${this.row}行 * ${this.col}列 = ${total}`
    });
  }

  /**
   * @inheritdoc
   * @param {*} distance
   */
  calcSeatTotla(distance) {
    const halfW = this.seatDiameter / 2;

    if (distance <= halfW) {
      return 0;
    }

    const count = (distance - halfW) / (this.seatDiameter + this.seatSpace);
    return Math.ceil(count);
  }
}

namespace.policy.canvas.MatrixSeatPolicy = MatrixSeatPolicy;
